<div class="page-header">
    <h2>用户管理</h2>
    <el-button type="primary" @click="showCreateDialog = true">新增用户</el-button>
</div>

<el-card>
    <el-table :data="userList" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="realName" label="真实姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="role" label="角色">
            <template #default="{row}">
                <el-tag :type="row.role === 'admin' ? 'danger' : 'success'">
                    ${ {'admin':'管理员','user':'用户','guest':'访客'}[row.role] }
                </el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="isActive" label="状态" width="80">
            <template #default="{row}">
                <el-switch
                    v-model="row.isActive"
                    @change="toggleUserStatus(row)"
                    :active-value="true"
                    :inactive-value="false">
                </el-switch>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
            <template #default="{row}">
                <el-button size="small" @click="editUser(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteUser(row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
</el-card>

<!-- 新增/编辑用户对话框 -->
<el-dialog :title="dialogTitle" v-model="showDialog" width="500px">
    <el-form :model="formData" :rules="formRules" ref="formRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
            <el-input v-model="formData.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="isCreate">
            <el-input v-model="formData.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
            <el-input v-model="formData.realName" placeholder="请输入真实姓名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
            <el-input v-model="formData.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
            <el-select v-model="formData.role" placeholder="请选择角色">
                <el-option label="管理员" value="admin"></el-option>
                <el-option label="用户" value="user"></el-option>
                <el-option label="访客" value="guest"></el-option>
            </el-select>
        </el-form-item>
    </el-form>
    <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
</el-dialog>

<script>
const { ref, reactive, computed } = Vue;
const { ElMessage, ElMessageBox } = ElementPlus;

export default {
    setup() {
        const loading = ref(false);
        const userList = ref([]);
        const showDialog = ref(false);
        const formRef = ref(null);
        const isCreate = ref(true);

        const formData = reactive({
            id: null,
            username: '',
            password: '',
            realName: '',
            email: '',
            role: 'user'
        });

        const formRules = {
            username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
            password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
            email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }]
        };

        const dialogTitle = computed(() => isCreate.value ? '新增用户' : '编辑用户');

        const loadUsers = async () => {
            loading.value = true;
            try {
                const response = await axios.get('/api/user');
                if (response.data.code === 200) {
                    userList.value = response.data.data;
                }
            } catch (error) {
                ElMessage.error('加载用户列表失败');
            } finally {
                loading.value = false;
            }
        };

        const editUser = (user) => {
            isCreate.value = false;
            Object.assign(formData, user);
            showDialog.value = true;
        };

        const submitForm = async () => {
            if (!formRef.value) return;

            try {
                await formRef.value.validate();
                const url = isCreate.value ? '/api/user' : '/api/user';
                const method = isCreate.value ? 'post' : 'put';

                const response = await axios[method](url, formData);
                if (response.data.code === 200) {
                    ElMessage.success(isCreate.value ? '创建成功' : '更新成功');
                    showDialog.value = false;
                    loadUsers();
                }
            } catch (error) {
                ElMessage.error('操作失败');
            }
        };

        const toggleUserStatus = async (user) => {
            try {
                const response = await axios.put(`/api/user/active/${user.id}/${user.isActive}`);
                if (response.data.code === 200) {
                    ElMessage.success('操作成功');
                }
            } catch (error) {
                ElMessage.error('操作失败');
                user.isActive = !user.isActive; // 恢复原状态
            }
        };

        const deleteUser = async (user) => {
            try {
                await ElMessageBox.confirm(`确定要删除用户 ${user.username} 吗？`, '警告', {
                    type: 'warning'
                });

                const response = await axios.delete(`/api/user/${user.id}`);
                if (response.data.code === 200) {
                    ElMessage.success('删除成功');
                    loadUsers();
                }
            } catch (error) {
                if (error !== 'cancel') {
                    ElMessage.error('删除失败');
                }
            }
        };

        loadUsers();

        return {
            loading,
            userList,
            showDialog,
            formRef,
            formData,
            formRules,
            dialogTitle,
            isCreate,
            editUser,
            submitForm,
            toggleUserStatus,
            deleteUser
        };
    }
};
</script>